﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Advertisement.Entity;
using NewRetail.Application.Components.Advertisement.Model;
using NewRetail.Application.Components.Platform;
using NewRetail.Application.Core;
using NewRetail.Application.Core.Entity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace NewRetail.Application.Components.Advertisement
{
    public interface IAdvertisementService : IApplicationService
    {
        /// <summary>
        /// 上传pos副屏广告图片
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        Task<(IEnumerable<AdvertisementPicResultDto>, string)> AddAdvertisementPics(AdvertisementPicAddDto inputDto);
    }
    public class AdvertisementService : ApplicationService, IAdvertisementService
    {
        private readonly IRepository<AdvertisementInfo> advertisementInfo;

        protected IEntityHelper _entityHelper => this.LazyServiceProvider.LazyGetRequiredService<IEntityHelper>();
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly string uploadName = "ResourceUploads";

        public AdvertisementService(IRepository<AdvertisementInfo> advertisementInfo, IWebHostEnvironment webHostEnvironment)
        {
            this.advertisementInfo = advertisementInfo;
            _webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// 上传pos副屏广告图片
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<(IEnumerable<AdvertisementPicResultDto>, string)> AddAdvertisementPics(AdvertisementPicAddDto inputDto)
        {
            var result = new List<AdvertisementPicResultDto>();
            if (string.IsNullOrEmpty(inputDto.warehouseId))
                return (null, "仓库不能为空！");
            try
            {
                //保存附件
                var records = new List<EnclosureDto>();
                if (inputDto.attachments != null && inputDto.attachments.Count > 0)
                {
                    //存附件
                    records.AddRange(await SaveAttachmentAsync(inputDto.attachments, inputDto.warehouseId));
                }
                if (records.Count > 0)
                {
                    
                    //获取表里最大sort
                    var db = await this.advertisementInfo.GetDbContextAsync();
                    var advertisements = await db.Set<AdvertisementInfo>().Where(x => x.warehouseId == inputDto.warehouseId && x.IsDeleted == false).ToArrayAsync();
                    var maxSort = (advertisements == null || advertisements.Count() == 0) ? 0 : advertisements.Max(s => s.sort);
                    int sort = maxSort + 1;
                    //存相关图片
                    var enclosures = new List<AdvertisementInfo>();
                    foreach (var item in records)
                    {
                        result.Add(new AdvertisementPicResultDto
                        {
                            fileName = item.fileName,
                            origionName = item.origionName,
                            ossPath = item.ossPath
                        });
                        enclosures.Add(new AdvertisementInfo
                        {
                            sort = sort,
                            warehouseId = inputDto.warehouseId,
                            extName = $"{item.fileName.Split('.').Last()}",
                            fileName = item.fileName,
                            origionName = item.origionName,
                            ossPath = item.ossPath,
                            enclosureType = item.enclosureType
                        });
                        sort++;
                    }
                    foreach (var m in enclosures)
                    {
                        _entityHelper.InitEntity(m);
                    }
                    await advertisementInfo.InsertManyAsync(enclosures, autoSave: true);
                }

                return (result, null);
            }
            catch (Exception e)
            {
                return (null, e.Message);
            }
        }

        #region 附件上传到服务器
        /// <summary>
        /// 把附件上传到服务器，返回文件名、地址
        /// </summary>
        /// <param name="formFiles"></param>
        /// <param name="warehouseId"></param>
        /// <returns></returns>
        private async Task<List<EnclosureDto>> SaveAttachmentAsync(IFormFileCollection formFiles, string warehouseId)
        {
            var attachments = new List<EnclosureDto>();

            try
            {
                var webRootPath = _webHostEnvironment.WebRootPath;
                var subDir = string.Concat("Belong_", warehouseId);
                //自动创建文件夹
                var directoryPath = Path.Combine(webRootPath, uploadName, subDir);
                if (!Directory.Exists(directoryPath))
                {
                    CreateFolder(directoryPath);
                }

                foreach (var file in formFiles)
                {
                    if (file.Length > 0)
                    {
                        //var fileId = Guid.NewGuid();
                        var timeStamp = DateTime.Now.Ticks;
                        var newFileName = $"{timeStamp}{file.FileName}";
                        //存到数据库地址
                        var savePath = Path.Combine(uploadName, subDir, newFileName);
                        var contentType = file.ContentType;
                        var fileName = Path.Combine(directoryPath, newFileName);

                        using (var stream = new FileStream(fileName, FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                            stream.Flush();
                            stream.Close();
                            attachments.Add(new EnclosureDto
                            {
                                origionName = file.FileName,
                                fileName = newFileName,
                                ossPath = savePath,
                                enclosureType = 1
                            });
                        }

                        //判断是否为图片，图片默认生成缩略图
                        //if (IsImageByName(file.FileName))
                        //{
                        //    var thumbName = Path.Combine(_hostEnvironment.ContentRootPath, "uploads", "reportup", DateTime.Now.ToString("yyyy-MM-dd"), "thumb", $"{timeStamp}{file.FileName}");

                        //    //CompressImage.CompressImg(fileName, thumbName, 20, 150);

                        //    Image iSource = Image.FromFile(fileName);
                        //    var orientation = (int)iSource.GetPropertyItem(274)?.Value[0];
                        //    Compress(new Bitmap(iSource), thumbName, 2);
                        //}
                    }
                }
            }
            catch (Exception)
            {
                attachments.Clear();
            }
            return attachments;
        }
        #endregion

        #region 创建文件夹
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="filefullpath"></param>
        /// <returns></returns>
        private DirectoryInfo CreateFolder(string filefullpath)
        {
            DirectoryInfo dir = null;
            if (!File.Exists(filefullpath))
            {
                string[] pathes = filefullpath.Split(Path.DirectorySeparatorChar);
                if (pathes.Length > 1)
                {
                    string path = pathes[0];
                    for (int i = 1; i < pathes.Length; i++)
                    {
                        path += Path.DirectorySeparatorChar + pathes[i];
                        if (!Directory.Exists(path))
                        {
                            dir = Directory.CreateDirectory(path);
                        }
                    }
                }
            }
            return dir;
        }

        #endregion
    }
}
